<!-- 游戏包打包配置编辑弹窗 -->
<template>
  <el-dialog
    :title="'打包配置'"
    :visible="visible"
    width="650px"
    :destroy-on-close="true"
    :lock-scroll="false"
    @update:visible="updateVisible"
    :close-on-click-modal="false"
    @open="queryGameOriginId"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="选择母包:" prop="game_origin_id">
        <el-select clearable v-model="form.game_origin_id" placeholder="请选择母包">
          <el-option v-for="(v, i) in gameOriginList" :key="i" :value="v.id" :label="v.version_code+'-'+v.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="icon:">
        <Upload
          :limit="1"
          :MaxSize="1024"
          :shardUpload="true"
          :chunkSize="100"
          :type="'images'"
          v-bind="{
            action: '/upload/zoneUpload?sdk_version=origin',
            multiple: false,
            accept: '.gif,.jpg,.jpeg,.png,.GIF,.JPG,.PNG',
            'list-type': 'picture-card'
          }"
          v-model="form.icon"
        >
          <i slot="button" class="el-icon-plus"></i>
        </Upload>
      </el-form-item>
      <el-form-item label="闪屏文件:">
        <!-- <el-upload
          accept=".gif,.jpg,.jpeg,.png,.GIF,.JPG,.PNG"
          class="avatar-uploader"
          :action="uploadImgUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove1"
          :before-remove="beforeRemove1"
          multiple
          :limit="1"
          :headers="myHeaders"
          :on-exceed="handleExceed"
          :file-list="fileList1"
          :http-request="uploadChunk1"
        >
          <img v-if="form.splash" :src="baseUrl + form.splash" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload> -->
        <Upload
          :limit="1"
          :MaxSize="1024"
          :shardUpload="true"
          :chunkSize="100"
          :type="'images'"
          v-bind="{
            action: '/upload/zoneUpload?sdk_version=origin',
            multiple: false,
            accept: '.gif,.jpg,.jpeg,.png,.GIF,.JPG,.PNG',
            'list-type': 'picture-card'
          }"
          v-model="form.splash"
        >
          <i slot="button" class="el-icon-plus"></i>
        </Upload>
      </el-form-item>
      <el-form-item label="闪屏类型:">
        <el-radio-group v-model="form.splash_type">
          <el-radio :label="0">不设置</el-radio>
          <el-radio :label="1">横屏</el-radio>
          <el-radio :label="2">竖屏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="签名方式:" prop="sign_type">
        <el-checkbox-group v-model="form.sign_type" v-if="visible">
          <el-checkbox label="default"></el-checkbox>
          <el-checkbox label="v1"></el-checkbox>
          <el-checkbox label="v2"></el-checkbox>
          <el-checkbox label="v3"></el-checkbox>
          <el-checkbox label="v4"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="版本名:" prop="version_name">
        <el-input
          v-model="form.version_name"
          :placeholder="'请输入版本名'"
        ></el-input>
      </el-form-item>
      <el-form-item label="版本号:" prop="version_code">
        <el-input
          v-model="form.version_code"
          :placeholder="'请输入版本号'"
        ></el-input>
      </el-form-item>
      <el-form-item label="目标版本:" prop="target_version">
        <el-input
          v-model="form.target_version"
          :placeholder="'请输入目标版本'"
        ></el-input>
      </el-form-item>
      <el-form-item label="编译版本:" prop="build_tools_version">
        <el-input
          v-model="form.build_tools_version"
          :placeholder="'请输入编译版本'"
        ></el-input>
      </el-form-item>
      <el-form-item label="架构方式:" prop="abi_type">
        <el-checkbox-group v-model="form.abi_type" v-if="visible">
          <el-checkbox label="default"></el-checkbox>
          <el-checkbox label="armeabi-v7a"></el-checkbox>
          <el-checkbox label="arm64-v8a"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="扩展资源地址:">
        <!-- <uploadFileZIP
          :limit="1"
          v-model="form.addition_res_path"
        ></uploadFileZIP> -->
        <Upload
          :limit="1"
          :MaxSize="1024"
          :shardUpload="true"
          :chunkSize="10"
          v-bind="{
            action: '/upload/zoneUpload?sdk_version=origin',
            multiple: true,
            accept: '.zip'
          }"
          v-model="form.addition_res_path"
        >
          <el-button slot="button" size="small" type="primary">
            点击上传
          </el-button>
          <div slot="tipTest">
            <div>
              只能上传zip格式的文件
            </div>
          </div>
        </Upload>
      </el-form-item>
      <el-form-item label="扩展信息:">
        <el-input
          type="textarea"
          :rows="3"
          v-model="form.addition_text"
          :placeholder="'请选择扩展信息'"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading"
        >保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
// import PageSelect from '@/components/pageSelect/index.vue'
import Upload from '@/components/upload/index'
import redioRuleData from '@/utils/rules'
import setting from '@/config/setting'
import md5 from 'js-md5' //引入MD5加密
export default {
  name: 'PackagePackageConfig',
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  components: { Upload },
  data() {
    let token = setting.takeToken()
    return {
      // 表单数据
      form: Object.assign({}),
      baseUrl: process.env.VUE_APP_API_BASE_URL,
      uploadImgUrl:
        process.env.VUE_APP_API_BASE_URL +
        '/upload/zoneUpload?sdk_version=origin',
      myHeaders: { Authorization: token },
      fileList: [],
      fileList1: [],
      // 表单验证规则
      rules: {
        game_origin_id: [
          { required: true, message: '请选择母包id', trigger: 'blur' }
        ],
        icon: [{ required: true, message: '请上传icon', trigger: 'blur' }],
        splash: [
          { required: true, message: '请上传闪屏文件', trigger: 'blur' }
        ],
        sign_type: [
          { required: true, message: '请选择签名方式', trigger: 'blur' }
        ],
        version_name: [
          { required: true, message: '请输入版本名', trigger: 'blur' }
        ],
        version_code: [
          { required: true, message: '请输入版本号', trigger: 'blur' }
        ],
        target_version: [
          { required: true, message: '请输入目标版本', trigger: 'blur' }
        ],
        build_tools_version: [
          { required: true, message: '请输入编译版本', trigger: 'blur' }
        ],
        abi_type: [
          { required: true, message: '请选择架构方式', trigger: 'blur' }
        ],
        addition_res_path: [
          { required: true, message: '请上传扩展资源地址', trigger: 'blur' }
        ],
        addition_text: [
          { required: true, message: '请输入扩展信息', trigger: 'blur' }
        ]
      },
      packageId: '',
      redios: redioRuleData(),
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // sdk_version_guanlian: ""
      game_origin_id: '',
      icon: '',
      splash: '',
      sign_type: ['default'],
      version_name: '',
      version_code: '',
      target_version: '',
      build_tools_version: '',
      abi_type: ['default'],
      addition_res_path: '',
      addition_text: '',
      save_sign_type: '',
      splash_type: 0,
      // 数组转字符串
      save_abi_type: '',
      // 数组转字符串
      save_form: {},
      gameOriginList:[],
    }
  },
  watch: {
    visible() {
      if (this.data && this.visible) {
        // console.log(this.data, "!!DDAA");
        this.form = Object.assign({
          game_origin_id: '',
          icon: '',
          splash: '',
          sign_type: ['default'],
          splash_type: 0,
          version_name: '',
          version_code: '',
          target_version: '',
          build_tools_version: '30.0.0',
          abi_type: ['default'],
          addition_res_path: ''
        })
        this.packageId = this.data.id
        this.$http
          .get('/Package/getPackageChannelConfig?package_id=' + this.packageId)
          .then((res) => {
            // console.log(res);
            if (res.data.code === 0) {
              if (res.data.data) {
                this.form = res.data.data
                this.form.sign_type = res.data.data.sign_type
                  ? res.data.data.sign_type.split(',')
                  : ['default'] // 存在且不为空的时候值为default
                this.form.abi_type = res.data.data.abi_type
                  ? res.data.data.abi_type.split(',')
                  : ['default'] // 存在且不为空的时候值为default
                // console.log(this.form, "fform");
                // console.log(res.data.data, "fffssssssssssssorm");
              } else {
                // console.log(this.form, "datakkong");
              }
            } else {
              this.$message.error(res.data.msg)
            }
          })
          .catch((e) => {
            this.$message.error(e.message)
          })

        this.isUpdate = true
      } else {
        this.form = {
          build_tools_version:'30.0.0'
        }
        this.save_form = {}
        this.isUpdate = false
      }
    }
  },
  methods: {
    //查詢母包id
    queryGameOriginId(){
      this.$http.post('/Gameorigin/index?game_id='+this.data.game_id).then(res=>{
        if(res.data.code === 0){
          this.gameOriginList=res.data.data
        }else{
          this.$message.error(res.data.msg)
        }
      })
    },
    handleRemove() {
      this.fileList = []
    },
    handleRemove1() {
      this.fileList1 = []
    },
    handlePreview(file) {
      console.log(file)
    },
    successUpload(response) {
      console.log(response)
    },
    handleExceed() {
      this.$message.warning(`当前限制选择 1 个文件`)
    },
    async beforeRemove(file) {
      try {
        await this.$confirm(`确定移除 ${file.name}？`)
        this.form.icon = ''
      } catch (error) {
        // 用户点击取消或关闭对话框时执行的代码，这里不需要做任何操作
      }
    },
    async beforeRemove1(file) {
      try {
        await this.$confirm(`确定移除 ${file.name}？`)
        this.form.splash = ''
      } catch (error) {
        // 用户点击取消或关闭对话框时执行的代码，这里不需要做任何操作
      }
    },
    // 分片上传文件
    async uploadChunk(file) {
      const totalSize = file.file.size
      // const totalSizeInMegabytes = totalSize / (1024 * 1024)
      // file_size
      // const totalSizeInMegabytesFixed = totalSizeInMegabytes.toFixed(2) + 'MB'

      const chunkSize = 10 * 1024 * 1024 // 10MB
      const chunkCount = Math.ceil(totalSize / chunkSize)
      const readChunkMD5 = async (chunk) => {
        return new Promise((resolve) => {
          let fileReaderInstance = new FileReader()
          fileReaderInstance.readAsBinaryString(chunk)
          fileReaderInstance.addEventListener('load', (e) => {
            let fileBlob = e.target.result
            let chunkMD5 = md5(fileBlob)
            resolve(chunkMD5)
          })
        })
      }

      const uploadChunkRecursive = async (index) => {
        if (index >= chunkCount) {
          return
        }
        // 更新当前分片数和总分片数
        this.currentChunk = index + 1

        const start = index * chunkSize
        const end = Math.min(start + chunkSize, totalSize)
        const chunk = file.file.slice(start, end)

        const chunkMD5 = await readChunkMD5(chunk)

        const formData = new FormData()
        // const Sdk_version = this.isUpdate
        //   ? this.form.file_type
        //   : this.sdk_version;
        formData.append('file', chunk)
        formData.append('chunkNumber', index + 1)
        formData.append('chunkSize', chunkSize)
        formData.append('currentChunkSize', chunk.size)
        formData.append('filename', file.file.name)
        formData.append('totalChunks', chunkCount)
        formData.append('md5', chunkMD5)
        try {
          const res = await this.$http.post(
            '/upload/zoneUpload?sdk_version=origin',
            formData
          )
          if (res.data.code === 2) {
            this.rules.file_url = [
              { required: false, message: '请上传文件', trigger: 'blur' }
            ]
            this.uploadProgress = Math.round(
              (this.currentChunk / chunkCount) * 100
            )
            this.form.icon = res.data.file_path

            this.$message.success(res.data.msg)
          } else if (res.data.code === 1) {
            this.uploadProgress = Math.round(
              (this.currentChunk / chunkCount) * 100
            )
            await uploadChunkRecursive(index + 1)
          }
        } catch (e) {
          this.loading = false
          this.$message.error(e.message)
        }
      }

      await uploadChunkRecursive(0)
    },
    // 分片上传文件
    async uploadChunk1(file) {
      const totalSize = file.file.size
      // const totalSizeInMegabytes = totalSize / (1024 * 1024)
      // file_size
      // const totalSizeInMegabytesFixed = totalSizeInMegabytes.toFixed(2) + 'MB'

      const chunkSize = 10 * 1024 * 1024 // 10MB
      const chunkCount = Math.ceil(totalSize / chunkSize)
      const readChunkMD5 = async (chunk) => {
        return new Promise((resolve) => {
          let fileReaderInstance = new FileReader()
          fileReaderInstance.readAsBinaryString(chunk)
          fileReaderInstance.addEventListener('load', (e) => {
            let fileBlob = e.target.result
            let chunkMD5 = md5(fileBlob)
            resolve(chunkMD5)
          })
        })
      }

      const uploadChunkRecursive = async (index) => {
        if (index >= chunkCount) {
          return
        }
        // 更新当前分片数和总分片数
        this.currentChunk = index + 1

        const start = index * chunkSize
        const end = Math.min(start + chunkSize, totalSize)
        const chunk = file.file.slice(start, end)

        const chunkMD5 = await readChunkMD5(chunk)

        const formData = new FormData()
        // const Sdk_version = this.isUpdate
        //   ? this.form.file_type
        //   : this.sdk_version;
        formData.append('file', chunk)
        formData.append('chunkNumber', index + 1)
        formData.append('chunkSize', chunkSize)
        formData.append('currentChunkSize', chunk.size)
        formData.append('filename', file.file.name)
        formData.append('totalChunks', chunkCount)
        formData.append('md5', chunkMD5)
        try {
          const res = await this.$http.post(
            '/upload/zoneUpload?sdk_version=origin',
            formData
          )
          if (res.data.code === 2) {
            this.rules.file_url = [
              { required: false, message: '请上传文件', trigger: 'blur' }
            ]
            this.uploadProgress = Math.round(
              (this.currentChunk / chunkCount) * 100
            )
            this.form.splash = res.data.file_path

            this.$message.success(res.data.msg)
          } else if (res.data.code === 1) {
            this.uploadProgress = Math.round(
              (this.currentChunk / chunkCount) * 100
            )
            await uploadChunkRecursive(index + 1)
          }
        } catch (e) {
          this.loading = false
          this.$message.error(e.message)
        }
      }

      await uploadChunkRecursive(0)
    },
    // 分片上传文件

    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        this.game_origin_id = this.form.game_origin_id
        this.icon = this.form.icon
        this.splash = this.form.splash
        this.sign_type = this.form.sign_type
        this.version_name = this.form.version_name
        this.version_code = this.form.version_code
        this.target_version = this.form.target_version
        this.build_tools_version = this.form.build_tools_version
        this.abi_type = this.form.abi_type
        this.addition_res_path = this.form.addition_res_path
        this.addition_text = this.form.addition_text
        this.splash_type = this.form.splash_type

        this.save_form.package_id = this.packageId
        this.save_form.game_origin_id = this.game_origin_id
        this.save_form.icon = this.icon
        this.save_form.splash = this.splash
        this.save_form.sign_type = this.sign_type.join(',')
        this.save_form.version_name = this.version_name
        this.save_form.version_code = this.version_code
        this.save_form.target_version = this.target_version
        this.save_form.build_tools_version = this.build_tools_version
        this.save_form.abi_type = this.abi_type.join(',')
        this.save_form.addition_res_path = this.addition_res_path
        this.save_form.addition_text = this.addition_text
        this.save_form.splash_type = this.splash_type
        if (valid) {
          this.loading = true
          this.form.package_id = this.packageId
          this.$http
            .post('/Package/setPackageChannelConfig', this.save_form)
            .then((res) => {
              this.loading = false
              if (res.data.code === 0) {
                this.$message.success(res.data.msg)
                if (!this.isUpdate) {
                  this.form = {}
                }
                this.updateVisible(false)
                this.$emit('done')
              } else {
                this.$message.error(res.data.msg)
              }
            })
            .catch((e) => {
              this.loading = false
              this.$message.error(e.message)
            })
        }
      })
    },

    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value)
      // console.log(this.form, "!!");
    }
  }
}
</script>

<style scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
